package com.example.skillcinema.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.skillcinema.R
import com.example.skillcinema.databinding.DialogCollectionItemBinding
import com.example.skillcinema.db.displaymodels.DialogCollection
import com.example.skillcinema.viewholders.DialogCollectionItemViewHolder

class DialogCollectionRecyclerViewAdapter(
    val toggle: (collection: DialogCollection) -> Unit,
    val createCollection: () -> Unit
) : RecyclerView.Adapter<DialogCollectionItemViewHolder>() {
    private var values: List<DialogCollection> = listOf()

    fun setData(list: List<DialogCollection>) {
        values = list
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(
        parent: ViewGroup, viewType: Int
    ): DialogCollectionItemViewHolder = DialogCollectionItemViewHolder(
        DialogCollectionItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    )

    override fun onBindViewHolder(
        holder: DialogCollectionItemViewHolder, position: Int
    ) {
        with(holder.binding) {
            if (position < itemCount - 1) {
                val item: DialogCollection = values[position]
                if (item.isInCollection) {
                    collectionImageView.setImageResource(R.drawable.ic_checkbox_fill)
                } else {
                    collectionImageView.setImageResource(R.drawable.ic_checkbox_unfill)
                }
                collectionNameTextView.text = item.name
                collectionCountTextView.text = item.count.toString()
                root.setOnClickListener {
                    toggle(item)
                }
            } else {
                collectionImageView.setImageResource(R.drawable.ic_plus)
                collectionCountTextView.text = ""
                collectionNameTextView.text =
                    root.resources.getString(R.string.dialog_add_to_collection)
                root.setOnClickListener {
                    createCollection()
                }
            }
        }
    }

    override fun getItemCount(): Int = values.count() + 1
}